<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ZPituitaryUser;
use App\Models\ZPituitaryUserExtend;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\ZPituitaryAnswer;
use App\Models\ZPituitaryUpload;
use App\Services\OssService;
use App\Services\CompleteService;

class AnswerController extends Controller {

    public $completeService;
    /**
     * AnswerController constructor.
     */
    public function __construct(CompleteService $completeService) {
         $this->completeService = $completeService;
    }

    /**
     * 获取章节列表
     * 垂体问卷 跟年龄 性别无关 但是可能跟用户所选的垂体类型有关暂定参数 ：用户 访视 类别 1 病史 2 实验室
     */
    public function getTemplates(Request $request) {
        $data = $request->all();
        $validator = Validator::make($data,
                        [
                            'user_id' => 'required',
                            'visit_level' => 'required',
                            'category_id' => 'required'
                        ],
                        [
                            'user_id.required' => '患者Id必须',
                            'visit_level.required' => '访视必须',
                            'category_id.required' => '章节类别必须'
                        ]
        );

        if ($validator->fails()) {
            return $this->error(42200, $validator->errors()->all()[0]);
        }

        $userId = $data['user_id'];
        $visitLevel = $data['visit_level'];
        $categoryId = $data['category_id'];
        // 每个大章节下的小章节信息


        $templates = DBSelect("
                select id,name,category_id,sort,has_chapter from z_pituitary_qss_template where id in (
                select c.template_id
                from  z_pituitary_control c
                left join z_pituitary_qss_template t on c.template_id = t.id
                where c.visit_level =$visitLevel   and t.category_id =$categoryId
                group by c.template_id
                 )  order by sort asc
                ");

        // 查询每个 template 是否答过题 标识
        $templateIds = collect($templates)->pluck('id')->toArray();
        $templateIdsStr = implode(',', $templateIds);

        $answers = DBSelect("select * from z_pituitary_answer where user_id =:userId and template_id in ($templateIdsStr) and visit_level =:visitLevel",
                ['userId' => $userId, 'visitLevel' => $visitLevel]);

        $answers = groupBy($answers, 'template_id');
        $index = 0;
        array_walk($templates, function (&$v, $k) use (&$index, $answers) {
            $v['index'] = $index;
            $index++;
            $templateId = $v['id'];
            $v['is_answered'] = false;
            if (isset($answers[$templateId])) {
                $v['is_answered'] = true;
            }
        });

        return $this->success($templates);
    }

    /**
     * 获取病史题目和答案
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function getQssInfo(Request $request) {
        $data = $request->all();
        $validator = Validator::make($data,
                        [
                            'user_id' => 'required',
                            'visit_level' => 'required',
                            'template_id' => 'required'
                        ],
                        [
                            'user_id.required' => '患者Id必须',
                            'visit_level.required' => '访视必须',
                            'template_id.required' => '章节必须'
                        ]
        );

        if ($validator->fails()) {
            return $this->error(42200, $validator->errors()->all()[0]);
        }

        $userId = $data['user_id'];
        $visitLevel = $data['visit_level'];
        $templateId = $data['template_id'];
        //如果章节是17-20 可能会有多组答案以及数据 这时候 返回的情况应该是按照组给对应的
        $groupData = [];
        if(in_array($templateId, [17,18,19,20])){
            $answers =  convertsArray(DB::select("select * from z_pituitary_answer  where user_id = $userId and visit_level = $visitLevel and  template_id = $templateId "));
            foreach($answers as $item){
                $groupData[$item['question_id']][$item['group_id']][] = $item;
            }
        }
        // 问卷题目 走 control 表每个v对应题目，连接answer表，整合成问卷数据
        $questions = convertsArray(DB::select("
               select q.template_id,q.chapter_id,q.question_id,q.question_name,q.subquestion_id,q.subquestion_name,q.subquestion_type,q.option_id,q.option_name,q.must_flg,
                a.answer_id,a.answer_name,a.unit,a.reference ,a.datasource ,a.date,a.group_id ,a.origin_time,a.origin_type,q.terminal_flg ,r.question_id as r_question_id,r.option_id as r_option_id,r.next_question_id as r_next_question_id
                from  z_pituitary_control c
                left join z_pituitary_question q on q.question_id = c.question_id
                left join  (select * from z_pituitary_answer  where user_id = $userId and visit_level = $visitLevel )  a on q.question_id = a.question_id   and a.answer_id = q.option_id
                left join z_pituitary_route r on q.question_id = r.question_id and q.option_id = r.option_id
                where c.visit_level = $visitLevel and c.template_id = $templateId
                ;"));

        // 根据规律发现 每一个 subquestion_id 就是一条数据，所以根据subquestion_id 做group处理
        $ques = collect($questions)->groupBy('subquestion_id')->toArray();
        $list = [];
        foreach ($ques as $que) {
            // 每条option 数据的question 部分都是一样的
            $item = [
                'answer' => [],
                'option' => [],
                'route' => [],
                'chapter_id' => $que[0]['chapter_id'],
                'must_flg' => $que[0]['must_flg'],
                'question_id' => $que[0]['question_id'],
                'question_name' => $que[0]['question_name'],
                'subquestion_id' => $que[0]['subquestion_id'],
                'subquestion_name' => $que[0]['subquestion_name'],
                'subquestion_type' => $que[0]['subquestion_type'],
                'template_id' => $que[0]['template_id'],
                'terminal_flg' => $que[0]['terminal_flg'],
                'visit_level' => $visitLevel,
                'unit' => $que[0]['unit'],
                'reference' => $que[0]['reference']
            ];

            if ($que[0]['r_question_id']) {
                $item['route'] = [
                    'question_id' => $que[0]['r_question_id'],
                    'next_question_id' => $que[0]['r_next_question_id'],
                    'option_id' => $que[0]['r_option_id'],
                ];
            }
            foreach ($que as $q) {
                $item['option'][] = [
                    'option_id' => $q['option_id'],
                    'option_value' => $q['option_name']
                ];
                if (!empty($q['answer_id'])) {
                    //过滤大于号和小于号
                    $replaceValueStart = str_replace('&amp;gt;', '>', $q['answer_name']);
                    $replaceValueEnd = str_replace('&amp;lt;', '<', $replaceValueStart);
                    //文件上传
                    if($q['answer_id'] == 156){
                        $replaceValueEnd = $this->getOssFiles($q['answer_name']);
                    }

                    $item['answer'][] = [
                        'answer_id' => $q['answer_id'],
                        'answer_value' => $replaceValueEnd,
                        'unit' => $q['unit'],
                        'reference' => $q['reference'],
                        'datasource' => $q['datasource'],
                        'origin_time' => $q['origin_time'],
                        'origin_type' => $q['origin_type'],
                        'terminal_flg' => $q['terminal_flg'],
                        'date' =>  $q['date'],
                        'group_id' =>  $q['group_id']
                    ];
                }
            }
            array_multisort($item['option']);
            $list[] = $item;
        }


        // 每个小章还有分类 chapter

        $chapters = convertsArray(DB::select("
                select * from z_pituitary_qss_chapter where template_id = $templateId and pid = 0
                "));

        $index = 0;
        array_walk($chapters, function (&$v, $k) use (&$index) {
            $v['index'] = $index;
            $index++;
        });
        // $groupData['bingcheng'] = DB::connection('pituitary')->table("z_user_bingcheng")->where('user_id',$userId)->first();
        // if (isset($groupData['bingcheng'])) {
        //     $groupData['bingcheng'] = $groupData['bingcheng']->bingcheng;
        // }
        $result = [
            'question_data' => $list,
            'chapter_data' => $chapters,
            'more_answer' =>  $groupData
        ];
        return $this->success($result);
    }

    /*
     * 获取上传的图片
     */
    public function getOssFiles($ids){
        if(!$ids){
            return "";
        }
        $idArr = explode(",",$ids);

        $ret =   ZPituitaryUpload::select(["id","file","date","filename"])->whereIn("id",$idArr)->get();
        $img = OssService::getInstance()->getPicUrl($ret);
        return $img;
    }

    /**
     * 保存章节下面的题目
     */
    public function saveQssInfo(Request $request) {
        $data = $request->all();
        $validator = Validator::make($data,
                        [
                            'user_id' => 'required',
                            'visit_level' => 'required',
                            'doc_id'    => 'required',
                            'data'  =>   'required'
                        ],
                        [
                            'user_id.required' => '患者Id必须',
                            'visit_level.required' => '访视必须',
                            'doc_id.required' => '操作医生必须',
                            'data.required' => '问卷必须'
                        ]
        );

        if ($validator->fails()) {
            return $this->error(42200, $validator->errors()->all()[0]);
        }

        $visitLevel = $data['visit_level'];
        $userId = $data['user_id'];
        $docId = $data['doc_id'];
        $templateIdKey = 11;

        //多参数时 这里是一个json
        $dataData =[];
        if(is_array($data['data'] ) && $data['data'] ){
            $dataData = $data['data'];
        }else {

            $data['data'] = stripslashes($data['data']);

            if($this->is_json($data['data'])){
               $dataData = json_decode($data['data'],1);
            }else{
                 return $this->error(42200, "参数格式错误");
            }

        }
            //保存病程
            // if(isset($data['bingcheng'])){
            //     $newBingcheng['user_id'] = $userId;
            //     $newBingcheng['update_at'] = date('Y-m-d H:i:s',time());
            //     $newBingcheng['bingcheng'] = $data['bingcheng'];
            //     $is_have_bingcheng = DB::connection('pituitary')->table("z_user_bingcheng")->where('user_id',$userId)->first();
            //     if (empty($is_have_bingcheng)) {
            //         DB::connection('pituitary')->table("z_user_bingcheng")->insert($newBingcheng);
            //     }else{
            //         DB::connection('pituitary')->table("z_user_bingcheng")->where('user_id',$userId)->update($newBingcheng);
            //     }
            // }

        foreach ($dataData as $template) {

            $templateId = $template['template_id'];
            $templateIdKey = $templateId;
            $oldAnswer = DBSelect("select * from z_pituitary_answer where user_id=$userId and visit_level= $visitLevel and template_id= $templateId");

             $insert = [];

            //实验室检查 可以自增题目
           if(in_array($templateId, [17,18,19,20])){
               foreach($template['answer'] as $k => $item){
                   foreach($item as   $answer){
                       if(!is_array($answer)){
                            return $this->error(42200, "参数格式错误");
                       }
                        $row = [];
                        $row['visit_level'] = $answer['visit_level'];
                        $row['user_id'] = $template['user_id'];
                        $row['doc_id'] = $template['doc_id'];
                        $row['template_id'] = $template['template_id'];
                        $row['terminal_flg'] = $template['terminal_flg'];
                        $row['chapter_id'] = $answer['chapter_id'];
                        $row['question_id'] = $answer['question_id'];
                        $row['subquestion_id'] = $answer['subquestion_id'];
                        $row['answer_id'] = $answer['answer_id'];
                        $row['answer_name'] = SBC_DBC($answer['answer_name']);
                        $row['datasource'] = $template['datasource'] ?? 2;
                        $row['unit'] = $template['unit'] ?? "";
                        //新增参数
                        $row['date'] = $answer['date'] ?? "0000-00-00";
                        $row['group_id'] = $k + 1;
                        $row['create_at'] = date('Y-m-d H:i:s', time());
                        $row['update_at'] = date('Y-m-d H:i:s', time());
                        $insert[] = $row;
                   }
                }
           }else{
                foreach ($template['answer'] as $answer) {
                    $row = [];
                    $row['visit_level'] = $answer['visit_level'];
                    $row['user_id'] = $template['user_id'];
                    $row['doc_id'] = $template['doc_id'];
                    $row['template_id'] = $template['template_id'];
                    $row['terminal_flg'] = $template['terminal_flg'];
                    $row['chapter_id'] = $answer['chapter_id'];
                    $row['question_id'] = $answer['question_id'];
                    $row['subquestion_id'] = $answer['subquestion_id'];
                    $row['answer_id'] = $answer['answer_id'];
                    $row['answer_name'] = SBC_DBC($answer['answer_name']);
                    $row['datasource'] = $template['datasource'] ?? 2;
                    $row['unit'] = $template['unit'] ?? "";
                    //新增参数
                    $row['date'] = $answer['date'] ?? "0000-00-00";
                    $row['group_id'] =  0;
                    $row['create_at'] = date('Y-m-d H:i:s', time());
                    $row['update_at'] = date('Y-m-d H:i:s', time());
                    $insert[] = $row;
             }
           }
            ZPituitaryAnswer::insertWithCompareData($oldAnswer, $insert, $userId, $visitLevel, $templateId, $docId);

        }

        //计算完成度
        if(in_array($templateIdKey, [11,12,13,14,15,16])){
            $this->completeService->completion($userId, $visitLevel);
        }


        return $this->success('');
    }


    public function is_json($string) {
            json_decode($string);
            return (json_last_error() == JSON_ERROR_NONE);
     }



    //上传图片后 返回图片id
    public function upload(Request $request){
          $params = $request->all();

        $validator = Validator::make($params,
                        [
                            'filedata' => 'required',
                            'user_id' => 'required',
                            'visit_level' => 'required',
                            'doc_id' => 'required'
                        ],
                        [
                            'filedata.required' => '文件必须',
                            'user_id.required' => '用户ID必须',
                            'visit_level.required' => '访视必须',
                            'doc_id.required' => '操作医生必须'
                        ]
        );

        if ($validator->fails()) {
             return $this->error(42200, $validator->errors()->all()[0]);
        }


        $file = $request->file('filedata');

        //创建文件夹
        $dirPath = storage_path('pituitary_file');
        if (!file_exists($dirPath)) {
            @mkdir($dirPath);
        }

        if ($file->isValid()) {
            //如果括号里面的不加上的话，下面的方法也无法调用的
            //获取文件的扩展名
            $ext = $file->getClientOriginalExtension();
            $ext = strtolower($ext);
            $check_ext = in_array($ext, ['jpg','jpeg','png','bmp','webp','gif','tif'], true);

            if (!$check_ext) {
                  return $this->error(42200, "不支持文件类型");
            }
            //定义文件名
            $filename = $file->getClientOriginalName();
            //
            //保存本地文件
            $file->move($dirPath, $filename);
            $localPath = $dirPath . DIRECTORY_SEPARATOR . $filename;
            $ossFile = 'pituitary_file' . DIRECTORY_SEPARATOR . date('Y-m-d') . DIRECTORY_SEPARATOR . $filename;

            $file = OssService::getInstance()->uploadFile($ossFile, $localPath);

            if(!$file){
                 return $this->error(42200, "文件上传错误");
            }

            $uploadFile =  ZPituitaryUpload::create([
                'user_id' => $params['user_id'],
                'doc_id' => $params['doc_id'],
                'file' => $file,
                'filename' => $filename,
                'date' => date('Y-m-d'),
                'visit_level' =>  $params['visit_level'],
            ]);
            $realURI = OssService::getInstance()->getPicUrl([$uploadFile]);
            return $this->success([
                "id" => $uploadFile->id,
//                "file" => $file
                "file" => $realURI[0]['file']
            ]);

        }
    }


    public function getCompletion(Request $request){
        $data = $request->all();
        $validator = Validator::make($data,
                        [
                            'user_id' => 'required',
                            'visit_level' => 'required'
                        ],
                        [
                            'user_id.required' => '患者Id必须',
                            'visit_level.required' => '访视必须'
                        ]
        );

        if ($validator->fails()) {
            return $this->error(42200, $validator->errors()->all()[0]);
        }
        $userId = $data['user_id'];
        $visitLevel = $data['visit_level'];
        $ret = $this->completeService->getCompletion($userId, $visitLevel);
        //第四项,合并症评估重新计算完成度
        $completion = ZPituitaryAnswer::complete($userId);
        //合并症评估重新赋值
        $ret['template_14'] = intval($completion);
        //重新计算总完成度
        $ret['bscj'] = round(($ret['template_11'] + $ret['template_12'] + $ret['template_13'] + $ret['template_14'] + $ret['template_15'] + $ret['template_16'])/6);
        return $this->success($ret);
    }

}
